package com.strive.village.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.strive.village.entity.TbResident;
import com.strive.village.entity.TbVillage;
import com.strive.village.entity.dto.VillageDto;
import com.strive.village.exception.EasyExcelException;
import com.strive.village.service.TbVillageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class DBVillageUploadUtils implements ReadListener<VillageDto> {

    private final List<TbVillage> cacheVillageList = new ArrayList<>();

    @Autowired
    TbVillageService villageService;

    /**
     * 读入一行数据的操作
     *
     * @param villageDto
     * @param analysisContext
     */
    @Override
    public void invoke(VillageDto villageDto, AnalysisContext analysisContext) {
        if (analysisContext != null) {
            // 初始化信息
            TbVillage village = new TbVillage();
            village.setVillageName(villageDto.getVillageName());
            village.setCounty(villageDto.getCounty());
            village.setPopulation(villageDto.getPopulation());
            village.setProvince(villageDto.getProvince());
            village.setEstablishData(villageDto.getEstablishData());
            village.setDescription(villageDto.getDescription());

            // 暂存
            cacheVillageList.add(village);

            if (cacheVillageList.size() >= 100) {
                // 插入数据库
                villageService.saveBatch(cacheVillageList);
                // 清空缓存
                cacheVillageList.clear();
            }
        } else {
            throw new EasyExcelException("文件为空");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 数据读取完毕
        villageService.saveBatch(cacheVillageList);
        cacheVillageList.clear();
    }
}
